/**
 * Analytics Service - 写写分析和AI使用统计服务
 * 基于 AI Writer Lite 的实现，为 IntelliMark 提供全面的数据分析和洞察
 */

import Store from 'electron-store'
import { v4 as uuidv4 } from 'uuid'

export interface WritingSession {
  id: string
  documentId: string
  startTime: number
  endTime?: number
  duration?: number
  wordCount: {
    start: number
    end: number
    added: number
    removed: number
  }
  characterCount: {
    start: number
    end: number
    added: number
    removed: number
  }
  aiOperations: AIOperation[]
  edits: EditOperation[]
  metadata: {
    device?: string
    platform?: string
    version?: string
  }
}

export interface AIOperation {
  id: string
  timestamp: number
  operation: 'polish' | 'expand' | 'translate' | 'fix_grammar' | 'change_tone' | 'summarize' | 'continue' | 'writing_guide'
  provider: string
  model: string
  input: {
    textLength: number
    wordCount: number
  }
  output: {
    textLength: number
    wordCount: number
  }
  performance: {
    responseTime: number
    tokensUsed: {
      prompt: number
      completion: number
      total: number
    }
    cost: number
  }
  success: boolean
  error?: string
  userRating?: number // 1-5
  userFeedback?: string
}

export interface EditOperation {
  id: string
  timestamp: number
  type: 'insert' | 'delete' | 'replace'
  position: number
  content: {
    before: string
    after: string
  }
  length: {
    before: number
    after: number
  }
  metadata: {
    source?: 'manual' | 'ai_assisted' | 'autocomplete'
    confidence?: number
  }
}

export interface DocumentAnalytics {
  documentId: string
  title?: string
  createdAt: number
  lastModified: number
  totalWritingTime: number
  sessionCount: number
  statistics: {
    totalWords: number
    totalCharacters: number
    averageWordsPerSession: number
    averageSessionDuration: number
    mostProductiveHour: number
    writingVelocity: number // words per hour
  }
  aiUsage: {
    totalOperations: number
    totalTokens: number
    totalCost: number
    operationsByType: Record<string, number>
    successRate: number
    averageResponseTime: number
  }
  qualityMetrics: {
    averageWordLength: number
    sentenceCount: number
    paragraphCount: number
    readabilityScore?: number
    complexityScore?: number
  }
}

export interface GlobalAnalytics {
  totalDocuments: number
  totalWritingTime: number
  totalWords: number
  totalSessions: number
  aiUsage: {
    totalOperations: number
    totalTokens: number
    totalCost: number
    providersUsage: Record<string, number>
    modelsUsage: Record<string, number>
    operationTypes: Record<string, number>
  }
  writingPatterns: {
    mostProductiveHour: number
    mostProductiveDay: number
    averageSessionDuration: number
    writingVelocity: number
    preferredOperations: Array<{ operation: string; count: number }>
  }
  trends: Array<{
    date: string
    wordsWritten: number
    timeSpent: number
    aiOperations: number
  }>
}

export interface AnalyticsSettings {
  enableTracking: boolean
  trackAIUsage: boolean
  trackWritingPatterns: boolean
  dataRetentionDays: number
  anonymizeData: boolean
  shareData: boolean
}

export class AnalyticsService {
  private store: Store
  private settings: AnalyticsSettings
  private currentSession: WritingSession | null = null

  constructor() {
    this.store = new Store({
      name: 'analytics',
      defaults: {
        sessions: {},
        documents: {},
        global: {
          totalDocuments: 0,
          totalWritingTime: 0,
          totalWords: 0,
          totalSessions: 0
        },
        settings: {
          enableTracking: true,
          trackAIUsage: true,
          trackWritingPatterns: true,
          dataRetentionDays: 90,
          anonymizeData: false,
          shareData: false
        }
      }
    })

    this.settings = this.store.get('settings') as AnalyticsSettings
  }

  /**
   * 开始写作会话
   */
  public startWritingSession(
    documentId: string,
    initialContent: string,
    metadata?: Partial<WritingSession['metadata']>
  ): string {
    if (!this.settings.enableTracking) {
      return ''
    }

    const sessionId = uuidv4()
    const wordCount = this.countWords(initialContent)
    const characterCount = initialContent.length

    this.currentSession = {
      id: sessionId,
      documentId,
      startTime: Date.now(),
      wordCount: {
        start: wordCount,
        end: wordCount,
        added: 0,
        removed: 0
      },
      characterCount: {
        start: characterCount,
        end: characterCount,
        added: 0,
        removed: 0
      },
      aiOperations: [],
      edits: [],
      metadata: {
        device: process.platform,
        platform: process.platform,
        version: '1.0.0', // 从package.json获取
        ...metadata
      }
    }

    console.log(`Started writing session ${sessionId} for document ${documentId}`)
    return sessionId
  }

  /**
   * 结束写作会话
   */
  public endWritingSession(finalContent: string): {
    sessionId: string
    duration: number
    wordsAdded: number
    wordsRemoved: number
  } | null {
    if (!this.currentSession || !this.settings.enableTracking) {
      return null
    }

    const endTime = Date.now()
    const duration = endTime - this.currentSession.startTime
    const finalWordCount = this.countWords(finalContent)
    const finalCharacterCount = finalContent.length

    // 更新会话数据
    this.currentSession.endTime = endTime
    this.currentSession.duration = duration
    this.currentSession.wordCount.end = finalWordCount
    this.currentSession.wordCount.added = Math.max(0, finalWordCount - this.currentSession.wordCount.start)
    this.currentSession.wordCount.removed = Math.max(0, this.currentSession.wordCount.start - finalWordCount)
    this.currentSession.characterCount.end = finalCharacterCount
    this.currentSession.characterCount.added = Math.max(0, finalCharacterCount - this.currentSession.characterCount.start)
    this.currentSession.characterCount.removed = Math.max(0, this.currentSession.characterCount.start - finalCharacterCount)

    // 保存会话
    this.saveSession(this.currentSession)

    // 更新文档分析
    this.updateDocumentAnalytics(this.currentSession.documentId, finalContent)

    // 更新全局统计
    this.updateGlobalAnalytics(this.currentSession)

    const result = {
      sessionId: this.currentSession.id,
      duration,
      wordsAdded: this.currentSession.wordCount.added,
      wordsRemoved: this.currentSession.wordCount.removed
    }

    console.log(`Ended writing session ${this.currentSession.id}`)
    this.currentSession = null

    return result
  }

  /**
   * 记录AI操作
   */
  public recordAIOperation(operation: Omit<AIOperation, 'id' | 'timestamp'>): void {
    if (!this.settings.trackAIUsage || !this.currentSession) {
      return
    }

    const aiOperation: AIOperation = {
      id: uuidv4(),
      timestamp: Date.now(),
      ...operation
    }

    this.currentSession.aiOperations.push(aiOperation)
  }

  /**
   * 记录编辑操作
   */
  public recordEdit(edit: Omit<EditOperation, 'id' | 'timestamp'>): void {
    if (!this.settings.trackWritingPatterns || !this.currentSession) {
      return
    }

    const editOperation: EditOperation = {
      id: uuidv4(),
      timestamp: Date.now(),
      ...edit
    }

    this.currentSession.edits.push(editOperation)
  }

  /**
   * 获取文档分析数据
   */
  public getDocumentAnalytics(documentId: string): DocumentAnalytics | null {
    return this.store.get(`documents.${documentId}`) as DocumentAnalytics || null
  }

  /**
   * 获取全局分析数据
   */
  public getGlobalAnalytics(): GlobalAnalytics {
    const sessions = this.getAllSessions()
    const documents = this.getAllDocumentsAnalytics()

    return this.calculateGlobalAnalytics(sessions, documents)
  }

  /**
   * 获取写作洞察
   */
  public getWritingInsights(documentId?: string): {
    productivityScore: number
    writingVelocity: number
    bestWritingTime: string
    aiEfficiency: number
    recommendations: string[]
    trends: Array<{
      date: string
      words: number
      time: number
    }>
  } {
    const sessions = documentId
      ? this.getDocumentSessions(documentId)
      : this.getAllSessions()

    const insights = this.calculateInsights(sessions)

    return insights
  }

  /**
   * 获取AI使用统计
   */
  public getAIUsageStats(
    timeRange?: { start: Date; end: Date }
  ): {
    totalOperations: number
    totalTokens: number
    totalCost: number
    operationBreakdown: Record<string, number>
    providerBreakdown: Record<string, number>
    modelBreakdown: Record<string, number>
    successRate: number
    averageResponseTime: number
    userSatisfaction: number
  } {
    const sessions = this.getAllSessions()
    let filteredSessions = sessions

    if (timeRange) {
      const startTime = timeRange.start.getTime()
      const endTime = timeRange.end.getTime()
      filteredSessions = sessions.filter(s =>
        s.startTime >= startTime && s.startTime <= endTime
      )
    }

    return this.calculateAIUsageStats(filteredSessions)
  }

  /**
   * 获取写作模式分析
   */
  public getWritingPatterns(documentId?: string): {
    mostProductiveHours: Array<{ hour: number; productivity: number }>
    mostProductiveDays: Array<{ day: number; productivity: number }>
    sessionLengthDistribution: Array<{ range: string; count: number }>
    writingVelocity: Array<{ date: string; velocity: number }>
    preferredOperations: Array<{ operation: string; count: number }>
  } {
    const sessions = documentId
      ? this.getDocumentSessions(documentId)
      : this.getAllSessions()

    return this.analyzeWritingPatterns(sessions)
  }

  /**
   * 导出分析数据
   */
  public exportData(
    format: 'json' | 'csv' = 'json',
    timeRange?: { start: Date; end: Date }
  ): string {
    const sessions = this.getAllSessions()
    let filteredSessions = sessions

    if (timeRange) {
      const startTime = timeRange.start.getTime()
      const endTime = timeRange.end.getTime()
      filteredSessions = sessions.filter(s =>
        s.startTime >= startTime && s.startTime <= endTime
      )
    }

    if (format === 'json') {
      return JSON.stringify({
        sessions: filteredSessions,
        documents: this.getAllDocumentsAnalytics(),
        global: this.getGlobalAnalytics(),
        exportedAt: new Date().toISOString()
      }, null, 2)
    } else {
      return this.convertToCSV(filteredSessions)
    }
  }

  /**
   * 清理旧数据
   */
  public cleanupOldData(): void {
    const retentionTime = this.settings.dataRetentionDays * 24 * 60 * 60 * 1000
    const cutoffTime = Date.now() - retentionTime

    const sessions = this.getAllSessions()
    const validSessions = sessions.filter(s => s.startTime >= cutoffTime)

    // 清理会话数据
    this.store.set('sessions', {})
    validSessions.forEach(session => {
      this.store.set(`sessions.${session.id}`, session)
    })

    // 清理文档分析数据
    const documents = this.getAllDocumentsAnalytics()
    Object.entries(documents).forEach(([documentId, analytics]) => {
      if (analytics.lastModified < cutoffTime) {
        this.store.delete(`documents.${documentId}`)
      }
    })

    console.log(`Cleaned up analytics data older than ${this.settings.dataRetentionDays} days`)
  }

  /**
   * 更新设置
   */
  public updateSettings(newSettings: Partial<AnalyticsSettings>): void {
    this.settings = { ...this.settings, ...newSettings }
    this.store.set('settings', this.settings)
  }

  /**
   * 获取设置
   */
  public getSettings(): AnalyticsSettings {
    return { ...this.settings }
  }

  // 私有方法

  private countWords(text: string): number {
    return text.trim().split(/\s+/).filter(word => word.length > 0).length
  }

  private saveSession(session: WritingSession): void {
    this.store.set(`sessions.${session.id}`, session)
  }

  private updateDocumentAnalytics(documentId: string, finalContent: string): void {
    const existing = this.getDocumentAnalytics(documentId) || {
      documentId,
      createdAt: Date.now(),
      lastModified: Date.now(),
      totalWritingTime: 0,
      sessionCount: 0,
      statistics: {
        totalWords: 0,
        totalCharacters: 0,
        averageWordsPerSession: 0,
        averageSessionDuration: 0,
        mostProductiveHour: 0,
        writingVelocity: 0
      },
      aiUsage: {
        totalOperations: 0,
        totalTokens: 0,
        totalCost: 0,
        operationsByType: {},
        successRate: 0,
        averageResponseTime: 0
      },
      qualityMetrics: {
        averageWordLength: 0,
        sentenceCount: 0,
        paragraphCount: 0
      }
    }

    // 更新文档分析
    existing.lastModified = Date.now()
    existing.totalWritingTime += this.currentSession?.duration || 0
    existing.sessionCount += 1
    existing.statistics.totalWords = this.countWords(finalContent)
    existing.statistics.totalCharacters = finalContent.length

    // 更新质量指标
    existing.qualityMetrics = this.calculateQualityMetrics(finalContent)

    this.store.set(`documents.${documentId}`, existing)
  }

  private updateGlobalAnalytics(session: WritingSession): void {
    const global = this.store.get('global') as any

    global.totalWritingTime += session.duration || 0
    global.totalWords += session.wordCount.added
    global.totalSessions += 1

    this.store.set('global', global)
  }

  private calculateQualityMetrics(content: string): DocumentAnalytics['qualityMetrics'] {
    const words = content.trim().split(/\s+/).filter(word => word.length > 0)
    const sentences = content.split(/[.!?]+/).filter(s => s.trim().length > 0)
    const paragraphs = content.split(/\n\n+/).filter(p => p.trim().length > 0)

    const totalWordLength = words.reduce((sum, word) => sum + word.length, 0)
    const averageWordLength = words.length > 0 ? totalWordLength / words.length : 0

    return {
      averageWordLength,
      sentenceCount: sentences.length,
      paragraphCount: paragraphs.length
    }
  }

  private getAllSessions(): WritingSession[] {
    const sessions = this.store.get('sessions') as Record<string, WritingSession>
    return Object.values(sessions).sort((a, b) => b.startTime - a.startTime)
  }

  private getDocumentSessions(documentId: string): WritingSession[] {
    const sessions = this.getAllSessions()
    return sessions.filter(s => s.documentId === documentId)
  }

  private getAllDocumentsAnalytics(): Record<string, DocumentAnalytics> {
    return this.store.get('documents') as Record<string, DocumentAnalytics>
  }

  private calculateGlobalAnalytics(
    sessions: WritingSession[],
    documents: DocumentAnalytics[]
  ): GlobalAnalytics {
    const analytics: GlobalAnalytics = {
      totalDocuments: documents.length,
      totalWritingTime: sessions.reduce((sum, s) => sum + (s.duration || 0), 0),
      totalWords: sessions.reduce((sum, s) => sum + s.wordCount.added, 0),
      totalSessions: sessions.length,
      aiUsage: {
        totalOperations: 0,
        totalTokens: 0,
        totalCost: 0,
        providersUsage: {},
        modelsUsage: {},
        operationTypes: {}
      },
      writingPatterns: {
        mostProductiveHour: 0,
        mostProductiveDay: 0,
        averageSessionDuration: 0,
        writingVelocity: 0,
        preferredOperations: []
      },
      trends: []
    }

    // 计算AI使用统计
    sessions.forEach(session => {
      session.aiOperations.forEach(op => {
        analytics.aiUsage.totalOperations++
        analytics.aiUsage.totalTokens += op.performance.tokensUsed.total
        analytics.aiUsage.totalCost += op.performance.cost

        analytics.aiUsage.providersUsage[op.provider] =
          (analytics.aiUsage.providersUsage[op.provider] || 0) + 1

        analytics.aiUsage.modelsUsage[op.model] =
          (analytics.aiUsage.modelsUsage[op.model] || 0) + 1

        analytics.aiUsage.operationTypes[op.operation] =
          (analytics.aiUsage.operationTypes[op.operation] || 0) + 1
      })
    })

    // 计算写作模式
    if (sessions.length > 0) {
      analytics.writingPatterns.averageSessionDuration =
        analytics.totalWritingTime / sessions.length

      analytics.writingPatterns.writingVelocity =
        analytics.totalWords / (analytics.totalWritingTime / (1000 * 60 * 60)) // words per hour
    }

    return analytics
  }

  private calculateInsights(sessions: WritingSession[]): any {
    // 实现洞察计算逻辑
    return {
      productivityScore: 0,
      writingVelocity: 0,
      bestWritingTime: '',
      aiEfficiency: 0,
      recommendations: [],
      trends: []
    }
  }

  private calculateAIUsageStats(sessions: WritingSession[]): any {
    // 实现AI使用统计计算
    return {
      totalOperations: 0,
      totalTokens: 0,
      totalCost: 0,
      operationBreakdown: {},
      providerBreakdown: {},
      modelBreakdown: {},
      successRate: 0,
      averageResponseTime: 0,
      userSatisfaction: 0
    }
  }

  private analyzeWritingPatterns(sessions: WritingSession[]): any {
    // 实现写作模式分析
    return {
      mostProductiveHours: [],
      mostProductiveDays: [],
      sessionLengthDistribution: [],
      writingVelocity: [],
      preferredOperations: []
    }
  }

  private convertToCSV(sessions: WritingSession[]): string {
    const headers = [
      'Session ID', 'Document ID', 'Start Time', 'Duration',
      'Words Added', 'Words Removed', 'AI Operations', 'Edit Count'
    ]

    const rows = sessions.map(session => [
      session.id,
      session.documentId,
      new Date(session.startTime).toISOString(),
      session.duration || 0,
      session.wordCount.added,
      session.wordCount.removed,
      session.aiOperations.length,
      session.edits.length
    ])

    return [headers, ...rows].map(row => row.join(',')).join('\n')
  }
}

// 导出单例实例
let analyticsServiceInstance: AnalyticsService | null = null

export function getAnalyticsService(): AnalyticsService {
  if (!analyticsServiceInstance) {
    analyticsServiceInstance = new AnalyticsService()
  }
  return analyticsServiceInstance
}